﻿package 
{
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.xml.XMLDocument;
	import sala.model.AlbumInfo;
	import sala.model.SalaInfo;
	import sala.model.VideoInfo;
	import sala.Sala;
	import sala.LanguageManager; 
	import sala.common.Configuration; 
	
	/**
	 * ...
	 * @author Sun
	 */
	public class Main extends Sprite 
	{
		public var salaApp: Sala;
		public var loader:URLLoader;
		
		public var engXML:XML; 
		public var engLoader:URLLoader; 
		public var vietLoader:URLLoader; 
		
		public function Main():void 
		{
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event = null):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			
			// entry point
			engLoader = new URLLoader(); 
			engLoader.load(new URLRequest(Configuration.RESOURCE_PATH + "xml/" + "sala_english.xml")); 
			engLoader.addEventListener(Event.COMPLETE, engXmlLoaderHld); 
			
			loader = new URLLoader(); 
			loader.load(new URLRequest(Configuration.RESOURCE_PATH + "xml/" + "right_menu.xml"));  
			loader.addEventListener(Event.COMPLETE, handleXMLLoaded);
			
		}
				
		private function engXmlLoaderHld(e:Event):void 
		{
			LanguageManager.setLanguageXML(XML(engLoader.data),"en"); 
			vietLoader = new URLLoader(); 
			vietLoader.load(new URLRequest(Configuration.RESOURCE_PATH + "xml/" + "sala_vietnamese.xml")); 
			vietLoader.addEventListener(Event.COMPLETE, vietXmlLoaderHld); 
			
		}
		
		private function vietXmlLoaderHld(e:Event):void 
		{
			LanguageManager.setLanguageXML(XML(vietLoader.data), "viet"); 
			
			LanguageManager.setLanguage("en");
			salaApp.updateText();
			
			salaApp.unlock(); 
		}
		
		public function handleXMLLoaded(e:Event):void  
		{  
			var xml:XML = XML(loader.data);  
			var albumInfoArr: Array = [];
			var albumInfo: AlbumInfo;
			var videoInfo: VideoInfo;
			var videoInfoArr: Array;
			var albumLength:uint = xml.album.length();
			var videoLength:uint;
			
			for (var i:uint = 0; i < albumLength; i++)
			{
				albumInfo = new AlbumInfo();
				albumInfo.albumIdx = i;
				albumInfo.name = xml.album[i].name;
				videoLength = xml.album[i].video.length();
				videoInfoArr = [];
				albumInfo.videoInfoArr = videoInfoArr;
				for (var j:uint = 0; j < videoLength; j++)
				{
					videoInfo = new VideoInfo();
					videoInfo.videoIdx = j;
					videoInfo.thumb = xml.album[i].video[j].thumb;
					videoInfo.link = xml.album[i].video[j].link;
					videoInfoArr.push(videoInfo);
				}
				
				albumInfoArr.push(albumInfo);
			}
			salaApp.initApp(albumInfoArr);
		}  
	}
	
}